﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace TopShooter.Editor.Actions
{
	public class PlaceTileAction : EditorAction
	{
		public List<Coordinate> Coordinates;
		public Tile NewTile;
		public List<Tile> OldTiles;

		public PlaceTileAction(Tile tile)
		{
			NewTile = tile;
			Coordinates = new List<Coordinate>();
			OldTiles = new List<Tile>();
		}
		public void AddLocation(Coordinate loc)
		{
			Coordinates.Add(loc);
		}
		public override string ToString()
		{
			return "PlaceTile:" + NewTile;
		}

		protected override bool OnApply(Scene scene)
		{
			bool isChanged = false;
			OldTiles.Clear();
			foreach (var c in Coordinates)
			{
				Tile t = scene.SetTile(NewTile, c);
				isChanged |= (t != NewTile);
				OldTiles.Add(t);
			}
			return isChanged;

		}

		protected override void OnUndo(Scene scene)
		{
			if (OldTiles.Count != Coordinates.Count)
				return;
			for (int i = 0; i < Coordinates.Count; i++)
			{
				Coordinate c = Coordinates[i];
				Tile t = OldTiles[i];
				scene.SetTile(t, c);
			}
			OldTiles.Clear();
		}

		protected override void AdjustLocation(int minColumn, int minRow)
		{
			for (int i = 0; i < Coordinates.Count; i++)
			{
				Coordinate c = Coordinates[i];
				c.Column -= minColumn;
				c.Row -= minRow;
				Coordinates[i] = c;
			}
		}
	}
}
